const axios = require('axios');
require('dotenv').config();

class DashScopeService {
    constructor() {
        this.apiKey = process.env.DASHSCOPE_API_KEY;
        this.baseUrl = process.env.DASHSCOPE_BASE_URL || 'https://dashscope.aliyuncs.com/api/v1';
        this.defaultModel = process.env.DEFAULT_MODEL || 'qwen-turbo';
        this.timeout = parseInt(process.env.API_TIMEOUT) || 30000;
        
        if (!this.apiKey) {
            throw new Error('DASHSCOPE_API_KEY is required in environment variables');
        }
        
        this.client = axios.create({
            baseURL: this.baseUrl,
            timeout: this.timeout,
            headers: {
                'Authorization': `Bearer ${this.apiKey}`,
                'Content-Type': 'application/json',
                'X-DashScope-SSE': 'disable'
            }
        });
    }

    async generateText(prompt, options = {}) {
        const {
            model = this.defaultModel,
            maxTokens = 2000,
            temperature = 0.7,
            topP = 0.8,
            stream = false
        } = options;

        try {
            const response = await this.client.post('/services/aigc/text-generation/generation', {
                model: model,
                input: {
                    messages: [
                        {
                            role: 'user',
                            content: prompt
                        }
                    ]
                },
                parameters: {
                    max_tokens: maxTokens,
                    temperature: temperature,
                    top_p: topP,
                    stream: stream,
                    result_format: 'message'
                }
            });

            if (response.data.output && response.data.output.choices && response.data.output.choices.length > 0) {
                return {
                    success: true,
                    content: response.data.output.choices[0].message.content,
                    usage: response.data.usage,
                    requestId: response.data.request_id
                };
            } else {
                throw new Error('No valid response from DashScope API');
            }
        } catch (error) {
            console.error('DashScope API Error:', error.response?.data || error.message);
            return {
                success: false,
                error: error.response?.data?.message || error.message,
                code: error.response?.data?.code || 'UNKNOWN_ERROR'
            };
        }
    }

    async generateArticle(topic, style = 'professional', length = 'normal') {
        const stylePrompts = {
            professional: '请用专业、严谨的写作风格',
            accessible: '请用通俗易懂、亲切的写作风格',
            humorous: '请用幽默风趣、生动的写作风格'
        };

        const lengthGuides = {
            short: '文章长度控制在800-1200字',
            normal: '文章长度控制在1500-2500字',
            long: '文章长度控制在3000-5000字'
        };

        const prompt = `作为一名资深的技术公众号作者，请根据以下要求写一篇技术文章：

主题：${topic}

写作要求：
1. ${stylePrompts[style] || stylePrompts.professional}
2. ${lengthGuides[length] || lengthGuides.normal}
3. 文章结构完整，包含引言、正文、总结
4. 适合微信公众号发布，段落简洁明了
5. 如涉及代码，请使用适当的代码示例
6. 语言流畅，逻辑清晰
7. 标题要有吸引力

请直接输出文章内容，不需要额外说明。`;

        return await this.generateText(prompt, {
            maxTokens: length === 'long' ? 4000 : length === 'short' ? 1500 : 2500,
            temperature: style === 'humorous' ? 0.8 : 0.7
        });
    }

    async getAvailableModels() {
        try {
            const response = await this.client.get('/services/aigc/text-generation/generation');
            return {
                success: true,
                models: response.data.models || []
            };
        } catch (error) {
            console.error('Failed to get available models:', error.response?.data || error.message);
            return {
                success: false,
                error: error.response?.data?.message || error.message,
                defaultModels: ['qwen-turbo', 'qwen-plus', 'qwen-max']
            };
        }
    }

    async testConnection() {
        try {
            const testPrompt = '请简单回复"连接测试成功"';
            const result = await this.generateText(testPrompt, { maxTokens: 50 });
            
            if (result.success) {
                return {
                    success: true,
                    message: '阿里云百炼API连接测试成功',
                    response: result.content,
                    usage: result.usage
                };
            } else {
                return {
                    success: false,
                    message: '阿里云百炼API连接测试失败',
                    error: result.error
                };
            }
        } catch (error) {
            return {
                success: false,
                message: '阿里云百炼API连接测试失败',
                error: error.message
            };
        }
    }
}

module.exports = DashScopeService;